package com.hongkuncheng.cms.controller.admin;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.DataitemReDepartment;
import com.hongkuncheng.cms.model.Department;
import com.hongkuncheng.cms.model.Zhuanti;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.model.Dataitem;
import com.hongkuncheng.cms.model.DataitemReColumns;
import com.hongkuncheng.cms.model.Datamodel;
import com.hongkuncheng.cms.model.Datasortfield;
import com.hongkuncheng.cms.model.Datasortmethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 数据项管理
 *
 * @author Administrator
 */
@Controller
@Transactional
@RequestMapping("admin/dataitem")
public class AdataitemController extends BaseController {

    // 数据项列表
    @RequestMapping
    public String index() {
        int datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
        Datamodel datamodel = factorySession.get(Datamodel.class, datamodelId);
        request.setAttribute("datamodel", datamodel);
        List<Dataitem> dataitems = factorySession.createCriteria(Dataitem.class)
                .add(Restrictions.eq("datamodel.id", datamodelId)).list();
        request.setAttribute("dataitems", dataitems);
        return view();
    }

    // 数据项编辑
    @RequestMapping("edit")
    public String edit() {
        int datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
        int dataitemId = request.getParameter("dataitemid") == null ? 0 :
                Integer.parseInt(request.getParameter("dataitemid"));
        Dataitem dataitem = dataitemId == 0 ? new Dataitem() : factorySession.get(Dataitem.class, dataitemId);
        List<Integer> columnsIds = new ArrayList<Integer>();
        List<Integer> departmentIds = new ArrayList<Integer>();
        if (dataitemId == 0) {
            dataitem.setDatasortfield1(factorySession.get(Datasortfield.class, 1));
            dataitem.setDatasortfield2(factorySession.get(Datasortfield.class, 2));
            dataitem.setDatasortfield3(factorySession.get(Datasortfield.class, 3));
        } else {
            for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) columnsIds.add(drc.getColumns().getId());
            for (DataitemReDepartment drd : dataitem.getDataitemReDepartments())
                departmentIds.add(drd.getDepartment().getId());
        }
        request.setAttribute("dataitem", dataitem);
        request.setAttribute("datamodelid", datamodelId);
        request.setAttribute("columnsids", columnsIds);
        request.setAttribute("departmentids", departmentIds);
        // 栏目集合
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        List<Integer> zhuantiIds = new ArrayList<Integer>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        List<Datasortfield> datasortfields = factorySession.createCriteria(Datasortfield.class).list();
        request.setAttribute("datasortfields", datasortfields);
        List<Department> departments = factorySession.createCriteria(Department.class).list();
        request.setAttribute("departments", departments);
        return view();
    }

    // 数据项编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_webmaintain_datamodel");
        int datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
        int dataitemId = Integer.parseInt(request.getParameter("dataitemid"));
        boolean pagesign = Boolean.parseBoolean(request.getParameter("pagesign"));
        if (pagesign) {
            int pagesigncount = Integer.parseInt(factorySession.createCriteria(Dataitem.class)
                    .add(Restrictions.eq("datamodel.id", datamodelId))
                    .add(Restrictions.eq("pagesign", true))
                    .add(Restrictions.ne("id", dataitemId))
                    .setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
            if (pagesigncount > 0) {
                PageHelper.alertAndGoBack("每一组数据项最多只能有一个分页标识");
                return;
            }
        }
        Dataitem dataitem = dataitemId == 0 ? new Dataitem() :
                factorySession.load(Dataitem.class, dataitemId, LockMode.PESSIMISTIC_WRITE);
        dataitem.setName(request.getParameter("name"));
        dataitem.setDataname(request.getParameter("dataname"));
        dataitem.setDatacount(Integer.parseInt(request.getParameter("datacount")));
        dataitem.setDynamiccolumns(request.getParameter("dynamiccolumns") != null);
        Datasortfield sortfieldid1 = factorySession.load(Datasortfield.class,
                Integer.parseInt(request.getParameter("sortfieldid1")));
        dataitem.setDatasortfield1(sortfieldid1);
        Datasortmethod sortmethodid1 = factorySession.load(Datasortmethod.class,
                Integer.parseInt(request.getParameter("sortmethodid1")));
        dataitem.setDatasortmethod1(sortmethodid1);
        Datasortfield sortfieldid2 = factorySession.load(Datasortfield.class,
                Integer.parseInt(request.getParameter("sortfieldid2")));
        dataitem.setDatasortfield2(sortfieldid2);
        Datasortmethod sortmethodid2 = factorySession.load(Datasortmethod.class,
                Integer.parseInt(request.getParameter("sortmethodid2")));
        dataitem.setDatasortmethod2(sortmethodid2);
        Datasortfield sortfieldid3 = factorySession.load(Datasortfield.class,
                Integer.parseInt(request.getParameter("sortfieldid3")));
        dataitem.setDatasortfield3(sortfieldid3);
        Datasortmethod sortmethodid3 = factorySession.load(Datasortmethod.class,
                Integer.parseInt(request.getParameter("sortmethodid3")));
        dataitem.setDatasortmethod3(sortmethodid3);
        dataitem.setDateastrict(Integer.parseInt(request.getParameter("dateastrict")));
        dataitem.setHaveimage(Boolean.parseBoolean(request.getParameter("haveimage")));
        dataitem.setPagesign(pagesign);
        List<Integer> columnsIds = DataHelper.convertToIntegerList(request.getParameterValues("columnsids"));
        List<Integer> departmentIds = DataHelper.convertToIntegerList(request.getParameterValues("departmentids"));
        if (dataitemId == 0) {
            Datamodel datamodel = factorySession.load(Datamodel.class, datamodelId);
            dataitem.setDatamodel(datamodel);
            factorySession.save(dataitem);
            recordLog("新建数据项《" + dataitem.getName().trim() + "》");
        } else {
            if (dataitem.getDataitemReColumnses().size() > 0) {
                // 删除原来的映射关系
                List<Object> drcs = new ArrayList<>();
                for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) {
                    if (!columnsIds.contains(drc.getColumns().getId())) drcs.add(drc);
                    else columnsIds.remove(Integer.valueOf(drc.getColumns().getId()));
                }
                factorySession.delete(drcs);
            }
            if (dataitem.getDataitemReDepartments().size() > 0) {
                // 删除原来的映射关系
                List<Object> drds = new ArrayList<>();
                for (DataitemReDepartment drd : dataitem.getDataitemReDepartments()) {
                    if (!departmentIds.contains(drd.getDepartment().getId())) drds.add(drd);
                    else departmentIds.remove(Integer.valueOf(drd.getDepartment().getId()));
                }
                factorySession.delete(drds);
            }
            recordLog("修改数据项《" + dataitem.getName().trim() + "》");
        }
        if (columnsIds.size() > 0) {
            // 创建新的映射关系
            List<Columns> columnses = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.in("id", columnsIds)).list();
            for (Columns columns : columnses) {
                DataitemReColumns drc = new DataitemReColumns();
                drc.setDataitem(dataitem);
                drc.setColumns(columns);
                factorySession.save(drc);
            }
        }
        if (departmentIds.size() > 0) {
            // 创建新的映射关系
            List<Department> departmentes = factorySession.createCriteria(Department.class)
                    .add(Restrictions.in("id", departmentIds)).list();
            for (Department department : departmentes) {
                DataitemReDepartment drd = new DataitemReDepartment();
                drd.setDataitem(dataitem);
                drd.setDepartment(department);
                factorySession.save(drd);
            }
        }
        recordLog((datamodelId == 0 ? "新建" : "更新") + "数据项《" + dataitem.getName().trim() + "》");
        PageHelper.alertAndRedirect("保存成功", "./?datamodelid=" + datamodelId);
    }

    // 数据项删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_webmaintain_datamodel");
        int datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
        int dataitemId = Integer.parseInt(request.getParameter("dataitemid"));
        Dataitem dataitem = factorySession.load(Dataitem.class, dataitemId, LockMode.PESSIMISTIC_WRITE);
        factorySession.delete(dataitem);
        recordLog("删除数据项《" + dataitem.getName().trim() + "》");
        PageHelper.alertAndRedirect("删除成功", "./?datamodelid=" + datamodelId);
    }

}
